package com.icesoft.base.manager.helper;


import com.icesoft.base.manager.security.config.ApiMatchAuthority;
import com.icesoft.core.common.exception.CodeErrorException;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 安全工具类
 *
 * @author xhh
 */
public class SecurityUtils {
    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     *
     * @param authentication 登录用户权限对象
     * @return BaseUser
     * <p>
     * 获取当前用户的全部信息 EnableBaseResourceServer true
     * 获取当前用户的用户名 EnableBaseResourceServer false
     */
    @Nullable
    public static AuthUser getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof AuthUser) {
            return (AuthUser) principal;
        }
        return null;
    }

    /**
     * 获取用户
     */
    @Nullable
    public static AuthUser getUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getUser(authentication);
    }

    @NonNull
    public static AuthUser getRequiredUser() {
        AuthUser user = getUser();
        if (user == null) {
            throw new CodeErrorException("用户为空");
        }
        return user;
    }

    public static boolean isSuperAdmin() {
        return isSuperAdmin(getUser());
    }

    public static boolean isSuperAdmin(AuthUser user) {
        return user != null && user.getId() == 1;
    }

    public static Stream<ApiMatchAuthority> getApiMatchAuthorityStream(Collection<? extends GrantedAuthority> gas) {
        return gas.stream().filter(ga -> ga instanceof  ApiMatchAuthority).map(ga->(ApiMatchAuthority)ga);
    }
    public static Set<ApiMatchAuthority> getApiMatchAuthority(Authentication authentication) {
        return getApiMatchAuthorityStream(authentication.getAuthorities()).collect(Collectors.toSet());
    }
    public static Set<ApiMatchAuthority> getApiMatchAuthority(AuthUser authUser) {
        return getApiMatchAuthorityStream(authUser.getAuthorities()).collect(Collectors.toSet());
    }
}
